package com.metagurukul.metaspace.actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.metagurukul.metaspace.controller.StatusDeleteForm;
import com.metagurukul.metaspace.models.beans.Comment;
import com.metagurukul.metaspace.service.StatusCommentService;

public class StatusDeleteAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ 
		StatusDeleteForm status = (StatusDeleteForm)form;
		int statusId = status.getStatusId();
		int commentId = status.getCommentId();
		
		String comment = status.getComment();
		int userId = (Integer) request.getSession().getAttribute("id");
		try {
			if(commentId > 0) {
				if(deleteComment(commentId) < 1){
					ActionMessages errors = new ActionMessages();
					errors.add("statusErr", new ActionMessage("com.metagurukul.metaspace.status.error.connectionNotCreated"));
					saveErrors(request, errors);	
				} 
			} else {
				if(comment.equals("")) {
					if(deleteStatus(statusId) < 1){
						ActionMessages errors = new ActionMessages();
						errors.add("statusErr", new ActionMessage("com.metagurukul.metaspace.status.error.connectionNotCreated"));
						saveErrors(request, errors);	
					} 
				} else {
					if(insertComment(statusId, userId, comment ) < 1){
						ActionMessages errors = new ActionMessages();
						errors.add("statusErr", new ActionMessage("com.metagurukul.metaspace.status.error.connectionNotCreated"));
						saveErrors(request, errors);	
					} 
				}
			}
			response.setHeader("Refresh", "0; URL=/jsp/status.jsp");
		} catch(SQLException se) {
			return mapping.findForward("failure");
		}
		
		return mapping.findForward("homePage");
	}
	
	public int deleteComment(int commentId) throws SQLException{
		return StatusCommentService.deleteComment(commentId);
	}
	
	public int deleteStatus(int statusId) throws SQLException{
		return StatusCommentService.deleteStatus(statusId);
	}
	
	public int insertComment(int statusId , int userId , String commentDesc) throws SQLException{
		Comment comment = new Comment();
		comment.setComment(commentDesc);
		comment.setUserId(userId);
		comment.setStatusId(statusId);
		return StatusCommentService.insertComment(comment);
	}
}
